<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue';
import axios, { AxiosRequestConfig } from 'axios';
import { ElTable, ElTableColumn, ElTag, ElLoading, ElIcon, ElMessage } from 'element-plus';
import { ArrowLeft } from "@element-plus/icons-vue";

// 定义变量
const orders = ref<any[]>([]);
const loading = ref(false);
let abortController: AbortController | null = null;

// 获取用户ID
const userId = computed(() => localStorage.getItem('userId') || '1');

// 状态类型映射
const getStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning';
    case 'completed': return 'success';
    case 'cancelled': return 'danger';
    default: return 'info';
  }
};

let controller = new AbortController();


onMounted(async () => {
  loading.value = true;
  abortController = new AbortController();

  try {
    const config: AxiosRequestConfig = {
      signal: abortController.signal
    };

    const res = await axios.get(`/api/orders/mySold?userId=${userId.value}`, config);
    orders.value = res.data;
  } catch (error) {
    if (axios.isCancel(error)) {
      console.log('请求被取消');
    } else {
      console.error('请求失败:', error);
      ElMessage.error('获取订单失败');
    }
  } finally {
    loading.value = false;
  }
});

onUnmounted(() => {
  controller.abort(); // 组件卸载时取消请求
});

const formatTime = (date: Date) => {
  if (!date) return '';
  // 简单格式化（根据需求调整）
  return date.toLocaleString();
};
</script>

<template>
  <div class="my-sold">
    <router-link to="/personal/" class="back-btn">
      <el-icon><ArrowLeft /></el-icon>
    </router-link>
    <h2>我卖出的订单</h2>

    <el-table
        :data="orders"
        border
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无卖出的订单"
    >
      <el-table-column prop="orderId" label="订单ID" align="center" />
      <el-table-column prop="productTitle" label="商品标题" align="center" />
      <el-table-column prop="price" label="价格" align="center" />
      <el-table-column prop="createTime" label="下单时间" align="center">
        <template #default="scope">
          <!-- 直接显示 createTime，或格式化 -->
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.my-sold {
  padding: 20px;
}
</style>